<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace Dwc\Wxapp;

/**
 * 微信小程序数据解密类.
 */
class WXBizDataCrypt
{
    /**
     * @var string
     */
    private string $appid;

    /**
     * @var string
     */
    private string $sessionKey;

    /**
     * 构造函数.
     */
    public function __construct(string $appid, string $sessionKey)
    {
        $this->appid = $appid;
        $this->sessionKey = $sessionKey;
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param string $encryptedData 加密的用户数据
     * @param string $iv 加密算法的初始向量
     */
    public function decryptData(string $encryptedData, string $iv): string
    {
        $aesKey = base64_decode($this->sessionKey);
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, 'AES-128-CBC', $aesKey, 1, $aesIV);
        $dataObj = json_decode($result);
        if ($dataObj == null) {
            return '';
        }
        if ($dataObj->watermark->appid != $this->appid) {
            return '';
        }
        return $result;
    }
}
